<!-- 管理 -->
<template>
  <div class="app-container">
    <!-- 列表 -->
    <el-col>
      <div v-if="isShowSearchBtn" class="search-container">
        <el-form ref="queryFormRef" :model="queryParams" :inline="true">
          <el-form-item label="关键字" prop="title">
            <el-input
              v-model="queryParams.title"
              placeholder="关键字"
              clearable
              style="width: 200px"
              @keyup.enter="handleQuery"
            />
          </el-form-item>

          <el-form-item label="类型" prop="type">
            <el-select
              v-model="queryParams.type"
              placeholder="全部"
              clearable
              class="!w-[120px]"
            >
              <el-option label="轮播图" value="1" />
              <el-option label="友情链接" value="2" />
              <el-option label="广告" value="3" />
            </el-select>
          </el-form-item>

          <el-form-item label="状态" prop="is_hid">
            <el-select
              v-model="queryParams.is_hid"
              placeholder="全部"
              clearable
              class="!w-[100px]"
            >
              <el-option label="启用" value="0" />
              <el-option label="禁用" value="1" />
            </el-select>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="handleQuery"
              ><i-ep-search />搜索</el-button
            >
            <el-button @click="resetQuery">
              <i-ep-refresh />
              重置</el-button
            >
          </el-form-item>
        </el-form>
      </div>

      <el-card shadow="never" class="table-container">
        <template #header>
          <div class="flex justify-between">
            <div>
              <el-button
                v-hasPerm="['resources@add']"
                type="success"
                @click="openDialog()"
                ><i-ep-plus />新增</el-button
              >
              <el-button
                v-hasPerm="['resources@del']"
                type="danger"
                v-if="removeIds.length > 0"
                @click="handleDelete()"
                ><i-ep-delete />删除</el-button
              >
            </div>
            <div>
              <el-button
                class="ml-3"
                @click="handleSearchShowBtn"
                icon="Search"
                circle
              />
              <el-button
                class="ml-3"
                title="刷新"
                @click="handleQuery"
                icon="Refresh"
                circle
              />
            </div>
          </div>
        </template>

        <el-table
          v-loading="loading"
          :data="pageData"
          @selection-change="handleSelectionChange"
          @sort-change="handleSortChange"
        >
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column
            key="id"
            label="ID"
            align="center"
            prop="id"
            width="100"
            sortable="custom"
          />
          <el-table-column label="标题" align="center" prop="title" />
          <el-table-column label="链接" align="center" prop="url" />
          <el-table-column label="类型" align="center">
            <template #default="scope">
              <span v-if="scope.row.type == 1"
                ><el-tag effect="dark">轮播图</el-tag></span
              >
              <span v-if="scope.row.type == 2"
                ><el-tag type="warning" effect="dark">友情链接</el-tag></span
              >
              <span v-if="scope.row.type == 3"
                ><el-tag type="success" effect="dark">广告</el-tag></span
              >
            </template>
          </el-table-column>
          <el-table-column label="描述" align="center" prop="description" />
          <el-table-column label="排序" align="center" prop="sort" />
          <el-table-column label="状态" align="center" prop="is_hid">
            <template #default="scope">
              <el-tag
                effect="dark"
                :type="scope.row.is_hid == 0 ? 'success' : 'danger'"
              >
                {{ scope.row.is_hid == 0 ? "启用" : "禁用" }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="创建时间" align="center" prop="created_at" />
          <el-table-column label="操作" fixed="right" width="220">
            <template #default="scope">
              <el-button
                v-hasPerm="['resources@edit']"
                type="success"
                circle
                title="编辑"
                @click="openDialog(scope.row.id)"
                ><i-ep-edit
              /></el-button>
              <el-button
                v-hasPerm="['resources@del']"
                circle
                type="danger"
                title="删除"
                @click="handleDelete(scope.row.id)"
                ><i-ep-delete
              /></el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-if="total > 0"
          v-model:total="total"
          v-model:page="queryParams.p"
          v-model:limit="queryParams.limit"
          @pagination="handleQuery"
        />
      </el-card>
    </el-col>

    <!-- 弹窗 -->
    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      :width="dialog.width"
      append-to-body
      @close="closeDialog"
    >
      <!-- 新增/编辑表单 -->
      <el-form
        ref="userFormRef"
        :model="formData"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="名称" prop="title">
          <el-input v-model="formData.title" placeholder="请输入名称" />
        </el-form-item>
        <el-form-item label="类型" prop="type">
          <el-radio-group v-model="formData.type" @change="resourceType">
            <el-radio-button label="轮播图" :value="1" />
            <el-radio-button label="友情链接" :value="2" />
            <el-radio-button label="广告" :value="3" />
          </el-radio-group>
        </el-form-item>

        <el-form-item label="图片" prop="img" v-if="isShowForm">
          <el-upload
            class="avatar-uploader"
            :action="uploadUrl"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
            :headers="headers"
          >
            <img
              v-if="formData.img"
              :src="formData.img"
              class="avatar"
              alt=""
            />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>

        <el-form-item label="链接" prop="title">
          <el-input v-model="formData.url" placeholder="请输入链接" />
        </el-form-item>

        <el-form-item label="描述" prop="description">
          <el-input
            v-model="formData.description"
            type="textarea"
            placeholder="请输入描述"
          />
        </el-form-item>

        <el-form-item label="排序" prop="sort">
          <el-input-number
            v-model="formData.sort"
            controls-position="right"
            :min="0"
            style="width: 100px"
          />
        </el-form-item>

        <el-form-item label="打开方式" prop="target_type">
          <el-radio-group v-model="formData.target_type">
            <el-radio :value="0">本窗口</el-radio>
            <el-radio :value="1">新窗口</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="状态" prop="is_hid">
          <el-radio-group v-model="formData.is_hid">
            <el-radio :value="0">正常</el-radio>
            <el-radio :value="1">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <!-- 弹窗底部操作按钮 -->
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
defineOptions({
  name: "Resources",
  inheritAttrs: false,
});

import type { UploadProps } from "element-plus";
import {
  getResourcesPage,
  addResources,
  updateResources,
  getResourcesForm,
  deleteResources,
} from "@/api/resources";
import {
  ResourcesForm,
  ResourcesQuery,
  ResourcesPage,
} from "@/api/resources/types";
const queryFormRef = ref(ElForm); // 查询表单
const userFormRef = ref(ElForm); // 用户表单
const isShowSearchBtn = ref(false);
const loading = ref(false); //  加载状态
const removeIds = ref([]); // 删除ID集合 用于批量删除
const isShowForm = ref(true);
const queryParams = reactive<ResourcesQuery>({
  p: 1,
  limit: 10,
});
const total = ref(0); // 数据总数
const pageData = ref<ResourcesPage[]>(); // 分页数据
// 弹窗对象
const dialog = reactive({
  visible: false,
  type: "user-form",
  width: 800,
  title: "",
});
// 表单数据
const formData = reactive<ResourcesForm>({
  is_hid: 0,
  type: 1,
  target_type: 0,
  sort: 0,
});
// 校验规则
const rules = reactive({
  title: [{ required: true, message: "名称不能为空", trigger: "blur" }],
});

const uploadUrl = ref(
  import.meta.env.VITE_APP_API_URL + "/admin/resources/upload"
);
const headers = ref({
  Authorization: localStorage.getItem("accessToken"),
});

const handleAvatarSuccess: UploadProps["onSuccess"] = (
  response,
  uploadFile
) => {
  formData.img = response.data.url;
};
const imageType = ["image/jpeg", "image/png", "image/jpg"];

const beforeAvatarUpload: UploadProps["beforeUpload"] = (rawFile) => {
  if (!imageType.includes(rawFile.type)) {
    ElMessage.error("图片格式不正确");
    return false;
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error("图片大小不超过 2MB!");
    return false;
  }
  return true;
};

/** 查询 */
function handleQuery() {
  loading.value = true;
  getResourcesPage(queryParams)
    .then(({ data }) => {
      pageData.value = data.items;
      total.value = data.total;
    })
    .finally(() => {
      loading.value = false;
    });
}

/** 重置查询 */
function resetQuery() {
  queryFormRef.value.resetFields();
  queryParams.p = 1;
  handleQuery();
}

/** 行选中 */
function handleSelectionChange(selection: any) {
  removeIds.value = selection.map((item: any) => item.id);
}

/**
 * 打开弹窗
 *
 * @param id
 */
async function openDialog(id?: number) {
  dialog.visible = true;
  // 表单弹窗
  if (id) {
    dialog.title = "修改";
    getResourcesForm(id).then(({ data }) => {
      Object.assign(formData, { ...data });
    });
  } else {
    dialog.title = "新增";
  }
}

/**
 * 关闭弹窗
 */
function closeDialog() {
  dialog.visible = false;
  userFormRef.value.resetFields();
  userFormRef.value.clearValidate();

  formData.id = undefined;
  formData.is_hid = 0;
  handleQuery();
}

/** 表单提交 */
const handleSubmit = useThrottleFn(() => {
  userFormRef.value.validate((valid: any) => {
    loading.value = true;
    if (valid) {
      const ids = formData.id;
      if (ids) {
        updateResources(formData)
          .then(() => {
            ElMessage.success("修改成功");
            closeDialog();
          })
          .finally(() => (loading.value = false));
      } else {
        addResources(formData)
          .then(() => {
            ElMessage.success("新增成功");
            handleQuery();
            closeDialog();
          })
          .finally(() => (loading.value = false));
      }
    }
  });
}, 3000);

/** 删除用户 */
function handleDelete(id?: number) {
  const ids = id || removeIds.value;
  if (!ids) {
    ElMessage.warning("请勾选删除项");
    return;
  }

  ElMessageBox.confirm("确认删除?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(function () {
    deleteResources({ ids: ids }).then(() => {
      handleQuery();
      ElMessage.success("删除成功");
      resetQuery();
    });
  });
}

//收起展开搜索按钮
function handleSearchShowBtn() {
  isShowSearchBtn.value = isShowSearchBtn.value === false;
}

function resourceType(value: any) {
  isShowForm.value = value != 2;
}

/** 排序 */
function handleSortChange(data: any) {
  const { prop, order } = data;
  if (prop === "id") {
    if (order === "ascending") {
      queryParams.sort = "+id";
    } else {
      queryParams.sort = "-id";
    }
    handleQuery();
  }
}

onMounted(() => {
  handleQuery();
});
</script>

<style>
.avatar-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 80px;
  height: 80px;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 80px;
  height: 80px;
  line-height: 80px;
  text-align: center;
}
.avatar {
  width: 80px;
  height: 80px;
  display: block;
}
</style>
